#include "socket.h"
#include <QThread>
#include <QMetaObject>
Socket::Socket(QTcpSocket *socket, int sum)
    : mySocket(socket)
    , sum(sum)
{

}

void Socket::socketInit()
{
    qDebug() << "socketInit" << QThread::currentThreadId();
    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    connect(mySocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(onStateChanged(QAbstractSocket::SocketState)));
    connect(mySocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}

void Socket::onStateChanged(QAbstractSocket::SocketState socketState)
{
    qDebug() << socketState;
    switch (socketState) {
    case QTcpSocket::ConnectedState:
        break;
    case QTcpSocket::UnconnectedState:
        emit signalDisconnect(sum);
        break;
    default:
        break;
    }
}

void Socket::onReadyRead()
{
    qint64 bas = mySocket->bytesAvailable();

    while (bas > 0) {
        if (mySocket->isValid() && mySocket->isReadable()) {
            emit signalSendToThread(mySocket->readAll());
        }
        else {
            qDebug() << "tcp socket not valid or not readable!";
        }

        bas = mySocket->bytesAvailable();
    }
}

void Socket::onSendToClient(QByteArray data)
{
    a++;
    qDebug() << "sendToclient" << a << "---" << data.size() << QThread::currentThreadId();;
    mySocket->write(data);
}
